#!/bin/sh

C=~/cache/handler.cache
TYPE=`jq -r .data[0].type $1`

[ $TYPE != GroupMessage ] && exit

GRPNO=`jq -r .data[0].sender.group.id $1`
MSG=`~/shbot/getmsg < $1` # e.g. {type: ..., text: ...}
MTYPE=`echo $MSG | jq -r .type`

send_reply ()
{
    ~/shbot/send $GRPNO "`cat $C`"
}

if [ $MTYPE == Image ]
then
    IID=`echo $MSG | jq -r .imageId`
    ~/bin/imghandler $IID > $C && send_reply
    exit
fi


[ $MTYPE != Plain ] && exit


MN=`jq -r .data[0].sender.memberName $1`
SENDER_ID=`jq -r .data[0].sender.id $1`
TXT=`echo $MSG | jq -r .text`
ISADMIN=$([ `cat ~/etc/adminid` -eq $SENDER_ID ] && echo "y")
ARG=`echo "$TXT" | sed -e 's/.\+ //' -e 's/\///g' -e 's/[\n\t\r :\/\\]//g'`

if echo "$TXT" | grep -i "^check"
then
    ~/shbot/check "$TXT" $GRPNO
    exit
fi

mycmd ()
{
    CMD=$1
    if echo "$TXT" | grep -i "^$CMD"
    then
        ~/shbot/$CMD $GRPNO $ARG
        exit
    fi
}

# mycmd bgraph
# mycmd rel
# mycmd uidname

replyworker ()
{
    ~/bin/replyworker "$TXT" "$ISADMIN" > $C || return 1
    send_reply
    return 0
}

rd ()
{
    RESP=`~/bin/rd "$TXT"`
    [ "$RESP" = '' ] && return 1
    echo "$RESP" > $C
    send_reply
    return 0
}

unoccupied ()
{
    RESP=`~/bin/calc_unoccupied "$SENDER_ID" "$TXT"`
    [ "$RESP" = '' ] && return 1
    echo "$RESP" > $C
    send_reply
    return 0
}

replyworker || rd || unoccupied || python3 ~/handler.py $GRPNO "$TXT" "$MN"

